/**
 * 
 */
package kjj.test.bluetooth.sample.clientserver;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

import javax.microedition.io.StreamConnection;

/**
 * @author kjj
 *
 */
public class ConnectedThread extends Thread {
	//debugging
	private static final boolean D =true;
	private static final String TAG = "ConnectedThread: ";
	
	private StreamConnection mStreamConnection = null;
	private final String answerString = "Response String from SPP Server:\n";
	
	/* constructor */
	public ConnectedThread(StreamConnection connection){
		mStreamConnection = connection;
	}
	
	@Override
	public void run()
	{
//		RemoteDevice dev = RemoteDevice.getRemoteDevice(connection);
//		System.out.println("Remote device address: "+dev.getBluetoothAddress());
//		System.out.println("Remote device name: "+dev.getFriendlyName(true));
		InputStream inStream;
		OutputStream outStream;
		try {
			//read string from spp client
			 inStream = mStreamConnection.openInputStream();
			//send response to spp client
			outStream =mStreamConnection.openOutputStream();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			return; // finish this thread.
		}

		BufferedReader bReader=new BufferedReader(new InputStreamReader(inStream));
		while (true)
		{
			try {
				String lineRead=bReader.readLine();
				System.out.println(lineRead);
				
				outStream.write(answerString.getBytes() );
				outStream.write(lineRead.getBytes());
				outStream.flush();

//				PrintWriter pWriter=new PrintWriter(new OutputStreamWriter(outStream));
//				pWriter.write("Response String from SPP Server\r\n");
//				pWriter.flush();
			} catch (IOException e) {
				// TODO: handle exception
//				e.printStackTrace();
				if (D) {
					System.out.println(TAG + "GoodBye");
				}
				break;
			}
		}
	}
	
}
